const { chromium } = require('playwright');

(async () => {
  const browser = await chromium.launch();
  const page = await browser.newPage();

  // 设置视窗大小
  await page.setViewportSize({ width: 1920, height: 1080 });

  // 监听控制台消息
  const consoleMessages = [];
  page.on('console', (msg) => {
    consoleMessages.push({
      type: msg.type(),
      text: msg.text(),
      location: msg.location()
    });
    console.log(`[${msg.type()}] ${msg.text()}`);
  });

  // 监听页面错误
  const pageErrors = [];
  page.on('pageerror', (error) => {
    pageErrors.push({
      message: error.message,
      stack: error.stack
    });
    console.log('页面错误:', error.message);
  });

  // 监听请求失败
  const failedRequests = [];
  page.on('requestfailed', (request) => {
    failedRequests.push({
      url: request.url(),
      error: request.failure().errorText
    });
    console.log('请求失败:', request.url(), request.failure().errorText);
  });

  try {
    console.log('开始详细测试 http://47.115.205.12/BCAI/...');

    // 访问目标页面
    const response = await page.goto('http://47.115.205.12/BCAI/', {
      waitUntil: 'networkidle',
      timeout: 30000
    });

    console.log('响应状态:', response.status());
    console.log('响应头:', response.headers());

    // 等待页面加载完成
    await page.waitForTimeout(10000);

    // 检查Vue应用是否正确挂载
    const appMounted = await page.evaluate(() => {
      const app = document.querySelector('#app');
      return app && app.__vue_app__ !== undefined;
    });
    console.log('Vue应用是否挂载:', appMounted);

    // 检查页面内容
    const pageContent = await page.evaluate(() => {
      const app = document.querySelector('#app');
      return {
        innerHTML: app ? app.innerHTML : 'No app element',
        children: app ? app.children.length : 0,
        hasContent: app ? app.innerHTML.trim().length > 0 : false
      };
    });
    console.log('页面内容:', pageContent);

    // 检查路由
    const currentRoute = await page.evaluate(() => {
      return window.location.pathname;
    });
    console.log('当前路由:', currentRoute);

    // 检查是否有任何可见元素
    const visibleElements = await page.$$eval('*', elements =>
      elements.filter(el => {
        const style = window.getComputedStyle(el);
        return style.display !== 'none' &&
               style.visibility !== 'hidden' &&
               style.opacity !== '0' &&
               el.offsetWidth > 0 &&
               el.offsetHeight > 0;
      }).length
    );
    console.log('可见元素数量:', visibleElements);

    // 检查具体的Element Plus组件
    const elementPlusComponents = await page.$$eval('.el-*', elements =>
      elements.map(el => el.className)
    );
    console.log('Element Plus组件:', elementPlusComponents);

    // 获取所有脚本标签
    const scripts = await page.$$eval('script', scripts =>
      scripts.map(script => ({
        src: script.src,
        loaded: script.complete,
        error: script.onerror !== null
      }))
    );
    console.log('脚本加载情况:', scripts);

    // 获取所有样式表
    const stylesheets = await page.$$eval('link[rel="stylesheet"]', links =>
      links.map(link => ({
        href: link.href,
        loaded: true // 简化检查
      }))
    );
    console.log('样式表加载情况:', stylesheets);

    console.log('\n=== 控制台消息汇总 ===');
    consoleMessages.forEach(msg => {
      console.log(`[${msg.type()}] ${msg.text}`);
    });

    console.log('\n=== 页面错误汇总 ===');
    pageErrors.forEach(error => {
      console.log('错误:', error.message);
      console.log('堆栈:', error.stack);
    });

    console.log('\n=== 失败请求汇总 ===');
    failedRequests.forEach(req => {
      console.log(`失败: ${req.url} - ${req.error}`);
    });

    // 最后截图
    await page.screenshot({ path: 'screenshot-detailed.png', fullPage: true });
    console.log('\n已保存详细截图到 screenshot-detailed.png');

  } catch (error) {
    console.error('测试过程中出错:', error.message);
    console.error('错误堆栈:', error.stack);
  } finally {
    await browser.close();
  }
})();